import { Module } from 'vuex'
import { getItem } from '@/utils/storage'
import type { ILoginState } from './type'
import type { IRootState } from '../type'

const loginModule: Module<ILoginState, IRootState> = {
  namespaced: true,
  state() {
    return {
      token: '',
      userInfo: {}
    }
  },
  mutations: {
    changeToken(state, token: string) {
      state.token = token
    },
    // 用户信息
    changeUserInfo(state, userInfo) {
      state.userInfo = userInfo
    }
  },
  actions: {
    // 数据持久化
    loadLocalLogin({ commit }) {
      const token = getItem('token')
      if (token) {
        commit('changeToken', token)
      }
      const userInfo = getItem('user_info')
      if (userInfo) {
        commit('changeUserInfo', userInfo)
      }
    }
  }
}
export default loginModule
